package com.flycent.hqhs.ui;


import java.lang.ref.WeakReference;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.Product;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.util.ShakeListenerUtils;
import com.flycent.hqhs.util.ShakeListenerUtils.OnShakeListener;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 摇一摇
 * @author fbl
 */
public class ShakeAvtivity extends BaseActivity {

	private Vibrator vibrator;//震动 

	/** 摇之前 遥之后 ,隐藏的 */
	private ImageView imView;
	/**监听*/
	private ShakeListenerUtils shakeListener;
	@SuppressWarnings("unused")
	private TextView countTextView;

	private	int icon[] = { R.drawable.shake_img_laft, R.drawable.shake_img_center,R.drawable.shake_img_right};

	private	int icoSotp[] = { R.drawable.shake_phone };
	private	int index = 0;

	//	private Product mProduct;
	private Product msSales;
	private  AlertDialog dlg;
	private Handler mHandler;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shake);

		mHandler = new MyHandler(this);
		
		init();
	}

	public void init(){
		vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);

		imView = (ImageView) this.findViewById(R.id.imgmiddle);
		countTextView = (TextView) this.findViewById(R.id.imgtit);

		shakeListener = new ShakeListenerUtils(this);
		shakeListener.setOnShake(onShake);


	}

	public void onClick(View v){
		switch (v.getId()) {
		case R.id.herd_back_icon:
			finish();
			break;

		default:
			break;
		}
	}


	/** 重力感应 */
	private OnShakeListener onShake = new OnShakeListener() {

		public void onShake() {
			startVibrator();

			shakeListener.stop();

			mHandler.sendEmptyMessageDelayed(0,200);
			mHandler.sendEmptyMessageDelayed(1, 200);
			
			
			


		}
	};
	
	
	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{
		
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if(mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					new Thread(){
						public void run() {
							try {
								msSales = WebClient.getInstance(ShakeAvtivity.this).rand();
								
								mHandler.sendEmptyMessageDelayed(2,2000);
							} catch (WebException e) {
								mHandler.sendEmptyMessage(3);
							}
						};
					}.start();
					
					break;
					
				case 1:
					if (index < icon.length - 1) {
						index++;
					} else {
						index = 0;
					}
					imView.setBackgroundResource(icon[index]);
					mHandler.sendEmptyMessageDelayed(1, 300);
					break;
				case 2:

					imView.setBackgroundResource(icoSotp[0]);
					mHandler.removeMessages(1);
					showaDialog();
					shakeListener.start();
					
					break;
				case 3:
					imView.setBackgroundResource(icoSotp[0]);
					App.showShortToast("出错了");
					mHandler.removeMessages(1);
					shakeListener.start();
					break;

				default:
					break;
				}
				
			}
			
		}
		
	
	}




		/*@SuppressLint("HandlerLeak")
		private Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					new Thread(
							new Runnable() {
								public void run() {
									Looper.prepare();//加入消息队列；
									try {
										msSales = WebClient.getInstance(ShakeAvtivity.this).rand();

										handler.sendEmptyMessageDelayed(2, 2000);

									} catch (Exception e) {
										handler.sendEmptyMessage(3);
									}

									Looper.loop();//加入消息队列；
								}
							}
							).start();
					break;
					
				case 1:
					
					if (index < icon.length - 1) {
						index++;
					} else {
						index = 0;
					}
					imView.setBackgroundResource(icon[index]);
					handler.sendEmptyMessageDelayed(1, 300);
				
					
					break;
				case 2:

					imView.setBackgroundResource(icoSotp[0]);
					handler.removeMessages(1);
					
					showaDialog();
					
					shakeListener.start();
	
				
					
					break;
				case 3:

					imView.setBackgroundResource(icoSotp[0]);
					App.showShortToast("出错了");
					handler.removeMessages(1);
					shakeListener.start();
				
					
					break;

				default:
					break;
				}
				
				
//				if(msg.what == 0){
//					
//					new Thread(
//							new Runnable() {
//								public void run() {
//									Looper.prepare();//加入消息队列；
//									try {
//										msSales = WebClient.getInstance(ShakeAvtivity.this).rand();
//
//										handler.sendEmptyMessageDelayed(2, 2000);
//
//									} catch (Exception e) {
//										handler.sendEmptyMessage(3);
//									}
//
//									Looper.loop();//加入消息队列；
//								}
//							}
//								).start();
//					
//				}else if(msg.what == 1) {
//	
//					if (index < icon.length - 1) {
//						index++;
//					} else {
//						index = 0;
//					}
//					imView.setBackgroundResource(icon[index]);
//					handler.sendEmptyMessageDelayed(1, 300);
//				} else if (msg.what == 2){
//					imView.setBackgroundResource(icoSotp[0]);
//					handler.removeMessages(1);
//					
//					showaDialog();
//					
//					shakeListener.start();
//	
//				}else if(msg.what == 3){
//					imView.setBackgroundResource(icoSotp[0]);
//					App.showShortToast("出错了");
//					handler.removeMessages(1);
//					shakeListener.start();
//				}
			}
		};*/

	@SuppressWarnings("unused")
	private class Handlers implements Runnable{
		
		public void run(){
			Looper.prepare();//加入消息队列；
			try {
				msSales = WebClient.getInstance(ShakeAvtivity.this).rand();

				mHandler.sendEmptyMessageDelayed(2, 2000);

			} catch (Exception e) {
				mHandler.sendEmptyMessage(3);
			}

			Looper.loop();//加入消息队列；
		}
	}

	/**
	 * 播放振动效果
	 */
	public void startVibrator() {
		vibrator.vibrate(new long[] { 500, 300, 500, 300 }, -1);
	}

	private void showaDialog(){
		dismisMyDialog();
		dlg = new AlertDialog.Builder(ShakeAvtivity.this).create();
		dlg.show();
		dlg.getWindow().setContentView(R.layout.product_dialog);
		LayoutInflater factory = LayoutInflater.from(ShakeAvtivity.this);
		View view = factory.inflate(R.layout.product_dialog, null);
		ImageView imageView = (ImageView) view.findViewById(R.id.product_image);
		TextView mText = (TextView) view.findViewById(R.id.product_name);
		TextView mpriceText = (TextView) view.findViewById(R.id.product_price);
		TextView mMarketpriceText = (TextView) view.findViewById(R.id.product_market_price);
		TextView mDiscountText = (TextView) view.findViewById(R.id.product_dialog_text1);
		ImageButton mNegativeBut = (ImageButton) view.findViewById(R.id.btn_negative);
		Button mpositiveBut = (Button) view.findViewById(R.id.btn_positive);
		RelativeLayout mProRelat = (RelativeLayout) view.findViewById(R.id.product_account_relat);

		mNegativeBut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				dlg.dismiss();
			}
		});
		mpositiveBut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				Intent intent = new Intent(ShakeAvtivity.this,ProductDetailActivity.class);
				intent.putExtra("productID", msSales.getId()+"");
				startActivity(intent);
				dlg.dismiss();
				ShakeAvtivity.this.finish();

			}
		});
		mProRelat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				Intent intent = new Intent(ShakeAvtivity.this,ProductDetailActivity.class);
				intent.putExtra("productID", msSales.getId()+"");
				startActivity(intent);
				dlg.dismiss();
				ShakeAvtivity.this.finish();

			}
		});

		ImageLoader.getInstance().displayImage(msSales.getImage(), imageView);
		mText.setText(msSales.getName());
		mpriceText.setText("￥"+msSales.getPrice());
		mMarketpriceText.setText("￥"+msSales.getReferencePrice());
		mMarketpriceText.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		float discont = msSales.getReferencePrice() - msSales.getPrice();
		mDiscountText.setText("掌上专享   立减"+((float)(Math.round(discont*100))/100));
		dlg.getWindow().setContentView(view);
	}

	private void dismisMyDialog() {

		if(  dlg != null && dlg.isShowing() ){
			dlg.dismiss();
		}
		dlg = null;

	}

	@Override
	protected void onDestroy() {
		dismisMyDialog();
		shakeListener.stop();
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}
















































	/* 

    private SensorManager sensorManager; 
    private Vibrator vibrator; 

    private static final String TAG = "TestSensorActivity"; 
    private static final int SENSOR_SHAKE = 10; 

	 *//** Called when the activity is first created. *//* 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_shake); 
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 
    } 




    @Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);
		titleBar.setTitle(R.string.title_shake);
	}




	@Override 
    protected void onResume() { 
        super.onResume(); 
        if (sensorManager != null) {// 注册监听器 
            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); 
            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率 
        } 
    } 

    @Override 
    protected void onStop() { 
        super.onStop(); 
        if (sensorManager != null) {// 取消监听器 
            sensorManager.unregisterListener(sensorEventListener); 
        } 
    } 

	  *//**
	  * 重力感应监听
	  *//* 
    private SensorEventListener sensorEventListener = new SensorEventListener() { 

        @Override 
        public void onSensorChanged(SensorEvent event) { 
            // 传感器信息改变时执行该方法 
            float[] values = event.values; 
            float x = values[0]; // x轴方向的重力加速度，向右为正 
            float y = values[1]; // y轴方向的重力加速度，向前为正 
            float z = values[2]; // z轴方向的重力加速度，向上为正 
            Log.i(TAG, "x轴方向的重力加速度" + x +  "；y轴方向的重力加速度" + y +  "；z轴方向的重力加速度" + z); 
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。 
            int medumValue = 19;// 三星 i9250怎么晃都不会超过20，没办法，只设置19了 
            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) { 
                vibrator.vibrate(200); 
                Message msg = new Message(); 
                msg.what = SENSOR_SHAKE; 
                handler.sendMessage(msg); 
            } 
        } 

        @Override 
        public void onAccuracyChanged(Sensor sensor, int accuracy) { 

        } 
    }; 

	   *//**
	   * 动作执行
	   *//* 
    @SuppressLint("HandlerLeak") 
    Handler handler = new Handler() { 

        @Override 
        public void handleMessage(Message msg) { 
            super.handleMessage(msg); 
            switch (msg.what) { 
            case SENSOR_SHAKE: 
            	App.showShortToast("检测到摇晃");
                break; 
            } 
        } 

    }; 
	    */


} 